昨天介紹資料庫的概念,今天會開始操作 Postgres 資料庫。GOGO!
以下示範均是直接對 postgres 的 terminal 進行操作哦!
(開啟 Postgres 並點選你要的 DB 就可以開啟)
psql -U 帳號 -h hostname -d database
\dt
\d 表名
CREATE TABLE IF NOT EXISTS schema_name.table_name(
column_name data_type [ DEFAULT default_expr ] [ column_constraint [ ... ] ]
);
CREATE TABLE IF NOT EXISTS public.train(
customer_id character varying(100) PRIMARY KEY,
sex character varying(1) NOT NULL,
height numeric(5,2) NOT NULL,
weight numeric(5,2) NOT NULL
);
INSERT INTO table [ ( column [, ...] ) ]
{ DEFAULT VALUES | VALUES ( { expression | DEFAULT } [, ...] ) | query }
INSERT INTO train(customer_id, sex, height, weight)
VALUES ('A123456789', 'M', '180.45', '70.7');
若一次想塞入多筆資料也可以辦得到!
INSERT INTO train(customer_id, sex, height, weight)
VALUES ('A123456789', 'M', '180.45', '70.7'),
('X123456789', 'M', '175.12', '65.7'),
('W123456789', 'W', '160.67', '45.7'),
('H123456789', 'W', '167.93', '52.7');
更新資料
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
UPDATE train set sex='F' where customer_id='A123456789';
篩選資料
SELECT [ ALL | DISTINCT [ ON ( expression [, ...] ) ] ]
all expression(*) [ AS output_name ] [, ...]
[ FROM from_item [, ...] ]
[ WHERE condition ]
[ GROUP BY expression [, ...] ]
[ HAVING condition [, ...] ]
[ { UNION | INTERSECT | EXCEPT } [ ALL ] select ]
[ ORDER BY expression [ ASC | DESC | USING operator ] [, ...] ]
[ LIMIT { count | ALL } ]
[ OFFSET start ]
[ FOR UPDATE [ OF table_name [, ...] ] ]
select * from train where sex='M';
刪除資料
DELETE FROM [ ONLY ] table [ WHERE condition ]
DELETE FROM train where sex='M';
清空一個表
TRUNCATE [ TABLE ] name
TRUNCATE train;
刪除表
DROP TABLE name [, ...] [ CASCADE | RESTRICT ]
DROP TABLE train;
給予其他人權限
GRANT { USAGE | ALL [ PRIVILEGES ] }
ON LANGUAGE lang_name [, ...]
TO { username | GROUP group_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]
GRANT ALL PRIVILEGES ON train to postgres;